﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace SharpSoft.WPF.Adorners
{
    /// <summary>
    /// 一个用于显示其他视图的对象的装饰器
    /// </summary>
    public class VisualAdorner : Adorner
    {
        private VisualCollection _visualCollection;
        public VisualAdorner(UIElement adornedElement) : base(adornedElement)
        {
            /*
             * 20200709
            VisualCollection父级指定为adornedElement后装饰器呈现的UI不刷新。暂不知道原因，遂指定VisualCollection的父级为装饰器本身。
            */
            _visualCollection = new VisualCollection(this);
            this.IsHitTestVisible = true;
        }
        /// <summary>
        /// 需要显示到装饰器的视图对象
        /// </summary>  
        public Visual ContentVisual
        {
            get { return (Visual)GetValue(ContentVisualProperty); }
            set { SetValue(ContentVisualProperty, value); }
        }

        public static readonly DependencyProperty ContentVisualProperty =
            DependencyProperty.Register("ContentVisual", typeof(Visual), typeof(VisualAdorner), new PropertyMetadata(null, (dpo, dpc) =>
            {
                if (dpo is VisualAdorner va)
                {
                    va._visualCollection.Clear();
                    va._visualCollection.Add(dpc.NewValue as Visual);
                }
            }));



        protected override int VisualChildrenCount => _visualCollection.Count;
        protected override Visual GetVisualChild(int index)
        {
            return _visualCollection[index];
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            if (this.ContentVisual is UIElement ue)
            {
                ue.Arrange(new Rect(finalSize));
            }
            return base.ArrangeOverride(finalSize);
        }
         
        //protected override void OnRender(DrawingContext dc)
        //{
        //    base.OnRender(dc);
        //    Rect rect = new Rect(this.AdornedElement.RenderSize);
        //    if (this.ContentVisual != null)
        //    {
        //        if (this.ContentVisual is FrameworkElement ele)
        //        {
        //            ele.Width = rect.Width;
        //            ele.Height = rect.Height;
        //        }
        //        VisualBrush vb = new VisualBrush(this.ContentVisual);
        //        dc.DrawRectangle(vb, null, rect);
        //    }
        //}
    }
}
